
# 拼多多订单列表查询接口

from common.Helper import Helper
from common.config import *
import time, requests,json
from threading import Thread
from pprint import pprint


class OrderCase( object ):

    def __init__(self):

        pass

    def signInfo(self,task):

        # print( task )
        # 生成当前时间戳
        ts = int(time.time())

        print( task )

        # 定义参数
        params = {

            'access_token': task['access_token'],
            'client_id': secret_key['client_id'],
            'type': 'pdd.order.list.get',
            'timestamp': '{0}'.format(ts),
            'order_status': '5',
            'refund_status': '5',
            'start_confirm_at': '{0}'.format( task['start_time']),
            'end_confirm_at': '{0}'.format( task['end_time']),
            'page': '{0}'.format( task['page']),
            'page_size': '100'

        }

        sign = Helper.genSign( params )

        params['sign'] = sign

        return params

    def requestJson(self,task):
        # 0 正常采集  1 token过期
        resp = {'type':100,'msg':'初始化任务','content':{}}

        param = self.signInfo( task )

        r = requests.post(url=api_router, data=json.dumps( param ), headers=headers,timeout=3)

        # print(r.json())


        # if r.status_code == 200 and 'access_token已过期' in json.dumps(r.json(),ensure_ascii=False):
        #
        #     print('AccessToken已经过期...')
        #     resp['content'] = task
        #     resp['content']['error'] = 1
        #     resp['content']['data'] = {}
        #
        #     content = Helper.changeBase64(json.dumps(resp['content']))
        #
        #     resp['content'] = content.decode('ascii')
        #
        #     return

        # 应用错误
        if r.status_code == 200 and 'error_response' in json.dumps(r.json(), ensure_ascii=False):


            warn = dict(error_code=r.json()['error_response']['error_code'],
                       error_msg=r.json()['error_response']['error_msg'])

            # print('error:',r.json()['error_response']['error_code'])
            resp['content']['content'] = task
            resp['content']['errcode'] = warn['error_code']
            resp['content']['errmsg'] = warn['error_msg']

            content = Helper.changeBase64(json.dumps(resp['content']))

            resp['content'] = content.decode('ascii')

            print(warn)

            return resp

        elif r.status_code == 200 and 'error_response' not in r.json():

            list = r.json()['order_list_get_response']['order_list']

            if len( list ) == 0:

                print('此时间段无订单数据信息')

                # 合并结果
                resp['content']['content'] = task
                resp['content']['errcode'] = 0
                resp['content']['errmsg'] = '任务完成'
                resp['content']['data'] = {}

                content = Helper.changeBase64(json.dumps(resp['content']))

                resp['content'] = content.decode('ascii')

                return resp

            pprint(list)

            resp['content']['content']  = task
            resp['content']['data'] = ( list )
            resp['content']['errcode'] = 0
            resp['content']['errmsg'] = '任务完成'

            content = Helper.changeBase64( json.dumps(resp['content']) )

            resp['content'] = content.decode('ascii')

            return resp

        else:

            print('拼多多服务端异常....')


    def parseJson(self):

        pass



if __name__ == '__main__':

    o = OrderCase()

    task = {
          "type": 201,
           "content":  {
            "task_page_id":  2,
             "task_id":  2,
             "owner_id":  186716817,
             "start_time":  1561651200,
             "end_time":  1561737599,
             "page":  1,
             "type":  0,
             "access_token":  "43fed277acb042648d0a6d0bdd98bddc2496e6d3"
          },
           "msg":  "订单列表任务"
        }

    task = task['content']

    o.requestJson(task)

    # threads = []
    #
    # for i in range(5):
    #
    #     t = Thread( target=o.main,args=())
    #
    #     t.start()
    #
    #     threads.append(t)
    #
    # for t in threads:
    #
    #     t.join()



